package main

import (
	"context"
	"fmt"
	"time"

	"github.com/docker/docker/api/types"

	"github.com/docker/go-connections/nat"

	"github.com/docker/docker/api/types/container"
	"github.com/docker/docker/client"
)

func main() {
	cli, err := client.NewClientWithOpts(client.FromEnv)
	if err != nil {
		panic(err)
	}

	// 查看所有容器
	/**
	containers, err := cli.ContainerList(context.Background(), types.ContainerListOptions{})
	if err != nil {
		panic(err)
	}

	for _, container := range containers {
		fmt.Printf("%s %s\n", container.ID[:10], container.Image)
	}
	*/

	resp, err := cli.ContainerCreate(
		context.Background(),
		&container.Config{
			Image: "mongo:4",
			ExposedPorts: nat.PortSet{
				"27017/tcp": {},
			},
		}, &container.HostConfig{
			PortBindings: nat.PortMap{
				"27017/tcp": []nat.PortBinding{
					{
						HostIP: "127.0.0.1",
						//HostPort: "27018",
						HostPort: "0", // 会自动映射到一个端口
					},
				},
			},
		}, nil, nil, "")

	if err != nil {
		panic(err)
	}

	err = cli.ContainerStart(context.Background(), resp.ID, types.ContainerStartOptions{})
	if err != nil {
		panic(err)
	}

	fmt.Println("container started", resp.ID)

	// 查看映射到了哪个端口
	inspRes, err := cli.ContainerInspect(context.Background(), resp.ID)
	if err != nil {
		panic(err)
	}
	fmt.Println("容器的端口映射在: ", inspRes.NetworkSettings.Ports)

	time.Sleep(time.Second * 5)

	err = cli.ContainerRemove(context.Background(), resp.ID, types.ContainerRemoveOptions{
		Force: true,
	})
	if err != nil {
		panic(err)
	}

	fmt.Println("container stop", resp.ID)
}
